package Controller;

import Dto.NewsTbEntity;
import Dto.UserTbEntity;
import MEx.MExAPI;
import repository.NewsRepository;
import repository.UserRepository;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;

@WebServlet(name = "NewsTable")
public class NewsTable extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public NewsTable(){
        super();
        //TODO Auto-generated constructor stub
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        try {
            NewsRepository newsRepository = new NewsRepository();
            Vector<NewsTbEntity> NewsList = newsRepository.getNewsTable();
            if(NewsList == null) {
                out.write("{\"Result\":\"FailB\"}");
                out.flush();
                out.close();
            }
            String json = "{\"NewsList\":[";

            for(NewsTbEntity model:NewsList)
            {
                String[] keys = {"Id","Headline","Name","UpTime","Check"};
                Object[] objs = {model.getNewsId(),model.getNewsHeadline(),model.getNewsName(),model.getUpTime(),model.getCheck()};
                json += MExAPI.toJson(keys,objs);
                if(model != NewsList.lastElement())
                    json+=",";
            }

            json += "],";

            json +="\"Result\": \"Success\"}";

            out.write(json);
        }
        catch (Exception e){
            e.printStackTrace();
            out.write("{\"Result\":\"Fail\"}");
        }
        finally{
            out.flush();
            out.close();
        }

    }
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
